package howl.Servlets;
import howl.types.*;
import howl.Twitter.EnableTwitter;
import howl.Twitter.TwitterProvider;
import howl.model.Model;
import howl.model.PMF;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class HowlEditUserServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		System.out.println(user);
		if (user == null) {

			resp.sendRedirect(userService.createLoginURL("/Signup.jsp"));

		}else {
			HowlUser hu = Model.getHowlUserfromUser(user);
		
			
			if(hu != null){
				resp.sendRedirect("/Auth/index.jsp");
			}else {
				resp.sendRedirect("/Signup.jsp");
			}
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		Model m;
		boolean email = !(req.getParameter("Email") == null);
		boolean rss = !(req.getParameter("Rss") == null);
		boolean twitter = !(req.getParameter("Twitter") == null);
		boolean layar = !(req.getParameter("Layar") == null);
		boolean yourflowingdata = !(req.getParameter("YourFlowingData") == null);
		boolean pachube = !(req.getParameter("Pachube") == null);
		String pachubeKey = req.getParameter("PachubeKey");

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		HowlUser u = Model.getHowlUserfromUser(user);
		m  = new Model(u);
		u = m.getHowlUser();
		if(pachube && pachubeKey != null){
			u.setPachubeKey(pachubeKey);
			u.setPachubeisConfigured(true);
		}
		

		u.setEmail(email);
		u.setRss(rss);
		u.setTwitter(twitter);
		u.setLayar(layar);
		u.setYourFlowingData(yourflowingdata);
		u.setPachube(pachube);
		if(!u.isTwitterisConfigured() && u.isTwitter()) {
			u.setFirstTimeUser(true);
			m.getPm().close();
			resp.sendRedirect( EnableTwitter.enableTwitter(user));
		}
		
		m.getPm().close();
		
        
		resp.sendRedirect("/Auth/index.jsp");

	}
}
